/*
    This is a set of libraries to assist in OpenGl and Other Applications
    Copyright (C) 2008  The Modular Engine Team

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#define TIMERMODULE
#include "TimerModule.h"

namespace ModularEngine
{
	void ExecuteTimer::update()
	{
		// If it's been executed, don't execute again
		if( !mbExecuted )
		{
			if( clock()-mtStartTime > mPeriod )
			{
				// Execute the functor
				(*mpFunctor)();
				mbExecuted = true;
			}
		}
	}

	void ExecuteTimer::reset()
	{
		// Reset to original state
		mbExecuted = false;
		mtStartTime = clock();
	}


	void PeriodicExecutor::startTimer( unsigned int uPeriod, Functor *pFunctor )
	{
		// Start the timer
		mPeriod = uPeriod;
		mpFunctor = pFunctor;
		TimerModule::getSingleton().addTimer( this );
	}

	void PeriodicExecutor::update()
	{
		// If the period has been met, execute it.
		if( clock()-mtStartTime > mPeriod )
		{
			// reset to original state and execute.
			reset();
			(*mpFunctor)();
		}
	}

	void Timer::update()
	{
		// For a normal timer, do nothing.  
		// Periodic executioner on the other hand gets to have more fun.

	}

	void Timer::reset()
	{
		// reset mtStartTime to current time = elapsed time.
		mtStartTime = clock();
	}

	time_t Timer::timeElapsed()
	{
		// current time - start time.
		return clock()-mtStartTime;
	}

	int TimerModule::initialize()
	{

		return 1;
	}

	int TimerModule::run()
	{
		// Update all the timers that matter.
		for( std::vector<Timer *>::iterator i = mvTimers.begin(); i != mvTimers.end(); i++ )
		{
			(*i)->update();
		}
		return 1;
	}

	void TimerModule::addTimer(ModularEngine::Timer *pTimer)
	{
		// Add timer to the list.
		mvTimers.push_back( pTimer );
	}


}

